package com.lvmama.pangolin.timer.processor;

import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.MissProduct;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.entity.hotel.HotelPdetail;
import com.lvmama.pangolin.entity.lmm.LMMCareProduct;
import com.lvmama.pangolin.hotel.service.HotelPdetailService;
import com.lvmama.pangolin.lmm.service.LMMCareProductService;
import com.lvmama.pangolin.service.EarlyWarningService;
import com.lvmama.pangolin.service.MissProductService;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.SpringContextUtil;
import com.lvmama.pangolin.util.WeixinUtil;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CheckLastHotelSpiderData extends CommonJob {
    @Autowired
    private LMMCareProductService careProductService;
    @Autowired
    private HotelPdetailService hotelPdetailService;
    @Autowired
    private MissProductService missProductService;

    @Autowired
    private TimerService timerService;

    @Autowired
    private EarlyWarningService earlyWarningService;

    private Logger logger = Logger.getLogger(CheckLastHotelSpiderData.class);

    @Override
    public void runJob(JobExecutionContext context, String parameter) {
        logger.info("开始检查数据...");
        String syscode = System.getProperties().getProperty("SYSCODE");
        if (timerService == null) {
            timerService = (TimerService) SpringContextUtil.getBean(TimerService.class);
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("syscode", syscode);
        Date currentdate = new Date();
        Calendar ccal = Calendar.getInstance();
        ccal.setTime(currentdate);
        ccal.add(Calendar.DAY_OF_MONTH, -1);
        String cron = new SimpleDateFormat("dd MM ? yyyy").format(ccal.getTime());
        param.put("timer_cron", cron);
        List<String> statusList = new ArrayList<String>();
        statusList.add("5");
        param.put("timer_status", statusList);
        param.put("job_code", Constant.HOTEL_BUS_TYPE);
        List<Timer> timerList = timerService.queryTimerHListByCon(param);
        try {
            String content = checkSpider(timerList, Constant.HOTEL_BUS_TYPE, ccal.getTime());
            if (StringTools.isValid(content)) {
                WeixinUtil.sendWchat(parameter, content);
            }

        } catch (Exception e) {
            logger.error("检查数据失败", e);
        }
        logger.info("结束检查数据...");
    }

    public String checkSpider(List<Timer> timerList, String businessCode, Date date) throws Exception {
        logger.info("检查抓取情况开始...");
        StringBuffer warnContent = new StringBuffer();
        if (timerList != null && timerList.size() > 0) {
            if (careProductService == null) {
                careProductService = (LMMCareProductService) SpringContextUtil.getBean(LMMCareProductService.class);
            }
            List<LMMCareProduct> careList = careProductService.getAll(null, null, null, businessCode);
            Map<String, List<LMMCareProduct>> map = new HashMap<String, List<LMMCareProduct>>();
            if (careList != null && !careList.isEmpty()) {
                List<LMMCareProduct> list = null;
                String cityCode = null;
                for (LMMCareProduct lmmCareProduct : careList) {
                    cityCode = lmmCareProduct.getCityCode();
                    list = map.get(cityCode);
                    if (list == null) {
                        list = new ArrayList<LMMCareProduct>();
                        list.add(lmmCareProduct);
                        map.put(cityCode, list);
                    } else {
                        list.add(lmmCareProduct);
                    }
                }
            }
            String city = null;
            String taskId = null;
            String paramCode = null;
            Date taskDate = null;
            String companyCode = null;
            String busiCode = null;
            ConfigManager config = ConfigManager.getInstance();
            Map<String, Object> paramMap = new HashMap<String, Object>();
            List<HotelPdetail> pist = null;
            List<MissProduct> missList = new ArrayList<MissProduct>();
            List<MissProduct> tcList = new ArrayList<MissProduct>();
            int tcCount = 0;
            List<MissProduct> xcList = new ArrayList<MissProduct>();
            int xcCount = 0;
            List<MissProduct> tnList = new ArrayList<MissProduct>();
            int tnCount = 0;
            List<MissProduct> qnrList = new ArrayList<MissProduct>();
            int qnrCount = 0;
            List<MissProduct> mtList = new ArrayList<MissProduct>();
            int mtCount = 0;
            List<MissProduct> elList = new ArrayList<MissProduct>();
            int elCount = 0;

            for (Timer timer : timerList) {
                city = timer.getGranularity_value();
                taskId = timer.getTask_id();
                paramCode = timer.getTimer_param();
                taskDate = timer.getCreate_time();
                List<LMMCareProduct> cityCareList = map.get(city);
                companyCode = config.getParamValue(timer.getTimer_param(), "COMPANY_CODE");
                busiCode = config.getParamValue(timer.getTimer_param(), "BUSINESS_CODE", Constant.HOTEL_BUS_TYPE);
                if (busiCode == null || !busiCode.equals(businessCode)) {
                    continue;
                }
                paramMap.put("task_id", taskId);
                paramMap.put("city_code", city);
                if (hotelPdetailService == null) {
                    hotelPdetailService = (HotelPdetailService) SpringContextUtil.getBean(HotelPdetailService.class);
                }
                switch(companyCode){
                    case "tc"  :
                        paramMap.put("company_code",Constant.TC_C_CODE);
                        pist = hotelPdetailService.queryCommodityListByTaskID(paramMap);
                        tcList.addAll(checkMissProduct(cityCareList, companyCode, pist, taskId, taskDate, paramCode));
                        tcCount += productCount(cityCareList, companyCode);
                        break;
                    case "xc"  :
                        paramMap.put("company_code",Constant.XC_C_CODE);
                        pist = hotelPdetailService.queryCommodityListByTaskID(paramMap);
                        xcList.addAll(checkMissProduct(cityCareList, companyCode, pist, taskId, taskDate, paramCode));
                        xcCount += productCount(cityCareList, companyCode);
                        break;
                    case "tn"  :
                        paramMap.put("company_code",Constant.TN_C_CODE);
                        pist = hotelPdetailService.queryCommodityListByTaskID(paramMap);
                        tnList.addAll(checkMissProduct(cityCareList, companyCode, pist, taskId, taskDate, paramCode));
                        tnCount += productCount(cityCareList, companyCode);
                        break;
                    case "qnr"  :
                        paramMap.put("company_code",Constant.QNR_C_CODE);
                        pist = hotelPdetailService.queryCommodityListByTaskID(paramMap);
                        qnrList.addAll(checkMissProduct(cityCareList, companyCode, pist, taskId, taskDate, paramCode));
                        qnrCount += productCount(cityCareList, companyCode);
                        break;
                    case "mt"  :
                        paramMap.put("company_code",Constant.MT_C_CODE);
                        pist = hotelPdetailService.queryCommodityListByTaskID(paramMap);
                        mtList.addAll(checkMissProduct(cityCareList, companyCode, pist, taskId, taskDate, paramCode));
                        mtCount += productCount(cityCareList, companyCode);
                        break;
                    case "el"  :
                        paramMap.put("company_code",Constant.EL_C_CODE);
                        pist = hotelPdetailService.queryCommodityListByTaskID(paramMap);
                        elList.addAll(checkMissProduct(cityCareList, companyCode, pist, taskId, taskDate, paramCode));
                        elCount += productCount(cityCareList, companyCode);
                        break;
                }

            }
            warnContent.append("酒店  ").append(new SimpleDateFormat("yyyy-MM-dd").format(date)).append("  抓取率统计信息：").append("\n");
            warnContent.append("TC抓取信息:     ").append("\n")
                    .append(content(tcList,tcCount)).append("\n");
            warnContent.append("XC抓取信息:   ").append("\n")
                    .append(content(xcList,xcCount)).append("\n");
            warnContent.append("TN抓取信息:     ").append("\n")
                    .append(content(tnList,tnCount)).append("\n");
            warnContent.append("QNR抓取信息:     ").append("\n")
                    .append(content(qnrList,qnrCount));
            warnContent.append("MT抓取信息:     ").append("\n")
                    .append(content(mtList,mtCount));
            warnContent.append("EL抓取信息:     ").append("\n")
                    .append(content(elList,elCount));
        }

        logger.info("检查抓取情况结束...");
        return warnContent.toString();
    }

    private String content(List<MissProduct> missList, int count) {
        StringBuffer sb = new StringBuffer("");
        StringBuffer sbs = new StringBuffer("");
        int size = 0;
        if (missList != null && !missList.isEmpty()) {
            size = missList.size();
            sbs.append(" 抓取失败产品:").append("\n");
            int i = 0;
            for (MissProduct missProduct : missList) {
                i++;
                if (i > 10) {
                    sbs.append("  ......").append("\n");
                    break;
                }

                sbs.append("  " + missProduct.getProductName()).append("\n");
            }
        }
        sb.append(" 抓取总数：" + count).append("\n");
        sb.append(" 抓取成功：" + (count - size)).append("\n");
        sb.append(" 抓取失败：" + size).append("\n");
        sb.append(" 抓取成功率：" + StringTools.getPercent((count - size), count, "##.00%"))
                .append("\n").append(sbs.toString());
        return sb.toString();

    }

    private int productCount(List<LMMCareProduct> careList, String companyCode) {
        int count = 0;
        if (careList != null && !careList.isEmpty()) {
            String url = null;
            for (LMMCareProduct careProduct : careList) {
                if ("tc".equals(companyCode)) {
                    url = careProduct.getTc_url();
                } else if ("xc".equals(companyCode)) {
                    url = careProduct.getXc_url();
                } else if ("tn".equals(companyCode)) {
                    url = careProduct.getTn_url();
                } else if ("qnr".equals(companyCode)) {
                    url = careProduct.getQnr_url();
                }else if ("mt".equals(companyCode)) {
                    url = careProduct.getMt_url();
                }else if ("el".equals(companyCode)){
                    url = careProduct.getYl_url();
                }
                if (StringTools.isValid(url)) {
                    count++;
                }

            }

        }

        return count;
    }

    private List<MissProduct> checkMissProduct(List<LMMCareProduct> careList, String companyCode, List<HotelPdetail> spiderList
            , String taskId, Date taskDate, String paramCode) {
        List<MissProduct> list = new ArrayList<MissProduct>();

        if (careList != null && !careList.isEmpty()) {
            String url = null;
            String name = null;
            String lvp = null;
            for (LMMCareProduct careProduct : careList) {
                lvp = careProduct.getProductId();
                if ("tc".equals(companyCode)) {
                    url = careProduct.getTc_url();
                    name = careProduct.getTc_name();
                } else if ("xc".equals(companyCode)) {
                    url = careProduct.getXc_url();
                    name = careProduct.getXc_name();
                } else if ("tn".equals(companyCode)) {
                    url = careProduct.getTn_url();
                    name = careProduct.getTn_name();
                } else if ("qnr".equals(companyCode)) {
                    url = careProduct.getQnr_url();
                    name = careProduct.getQnr_name();
                 } else if ("mt".equals(companyCode)) {
                    url = careProduct.getMt_url();
                    name = careProduct.getMt_name();
                }else if ("el".equals(companyCode)){
                    url = careProduct.getYl_url();
                    name = careProduct.getYl_name();
                }
                boolean spiderFlag = false;
                if (!StringTools.isValid(url)) {
                    spiderFlag = true;

                }
                if (spiderList != null && !spiderList.isEmpty()) {
                    for (HotelPdetail product : spiderList) {
                        if (url != null && url.equalsIgnoreCase(product.getDetailUrl())) {
                            spiderFlag = true;
                        }
                        if (url != null && product.getDetailUrl().contains(url)) {
                            spiderFlag = true;
                        }
                        if (name != null && name.trim().equalsIgnoreCase(product.getHotelName().trim())) {
                            spiderFlag = true;
                        }
                        if (lvp != null && lvp.equalsIgnoreCase(product.getProductId())) {
                            spiderFlag = true;
                        }

                    }
                }
                if (!spiderFlag) {
                    MissProduct missProduct = new MissProduct();
                    missProduct.setBusinessCode(careProduct.getBusinessCode());
                    missProduct.setCityCode(careProduct.getCityCode());
                    missProduct.setCityName(careProduct.getCityName());
                    missProduct.setCompanyCode(companyCode);
                    missProduct.setDealFlag(0);
                    missProduct.setProductId(lvp);
                    missProduct.setProductName(careProduct.getProductName());
                    missProduct.setName(name);
                    missProduct.setUrl(url);
                    Date date = new Date();
                    missProduct.setInsertTime(new Timestamp(date.getTime()));
                    missProduct.setUpdateTime(new Timestamp(date.getTime()));
                    missProduct.setTaskDate(taskDate);
                    missProduct.setTaskId(taskId);
                    missProduct.setParamCode(paramCode);
                    list.add(missProduct);

                }
            }

        }

        return list;
    }


}
